package com.ccp.dev.workflow.service;

import com.ccp.dev.core.basic.base.BaseService;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.workflow.dao.BpmProStatusDao;
import com.ccp.dev.workflow.model.BpmProStatus;
import com.ccp.dev.workflow.model.FlowNodeInfo;
import com.ccp.dev.workflow.model.NodeCache;
import com.ccp.dev.workflow.model.TaskOpinion;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassDescribe:流程节点状态 Service
 * @author :jiayueqiao
 * Date: 2019-07-31
 * Since:1
 */
@Service
public class BpmProStatusService extends BaseService<BpmProStatus> {


    @Resource
    private BpmProStatusDao dao;

    /**
     * 添加流程数据状态。
     *
     * @param procDefId
     *            流程定义ID
     * @param procInstId
     *            流程实例ID
     * @param nodeId
     *            节点ID
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpd(String procDefId, String procInstId, String nodeId) {
        addOrUpd(procDefId,procInstId,nodeId,TaskOpinion.STATUS_CHECKING);
    }

    /**
     * 添加或修改节点的执行状态。
     * @param procDefId 流程定义id
     * @param procInstId 流程实例id
     * @param nodeId 节点id
     * @param status 状态
     */
    @Transactional(rollbackFor = Exception.class)
    public void addOrUpd(String procDefId, String procInstId, String nodeId,Short status) {
        BpmProStatus bpmProStatus = dao.getByInstNodeId(procInstId, nodeId);
        if (bpmProStatus == null) {
            Map<String, FlowNodeInfo> mapNode = NodeCache.getByProcDefId(procDefId);
            BpmProStatus tmp = new BpmProStatus();
            tmp.setId(UUIDUtils.getUUIDFor32());
            tmp.setProcDefId(procDefId);
            tmp.setProcInstId(procInstId);
            tmp.setLastUpdateTime(new Date());
            tmp.setNodeId(nodeId);
            tmp.setStatus(status);
            FlowNodeInfo flowNode = mapNode.get(nodeId);
            tmp.setNodeName(flowNode.getNodeName());
            dao.add(tmp);
        } else {
            this.updStatus(procInstId, nodeId, status);
        }
    }

    /**
     * 更新状态
     * @param procInstId 流程实例id
     * @param nodeId 节点id
     * @param status 状态
     * @return 返回值
     */
    @Transactional(rollbackFor = Exception.class)
    public int updStatus(String procInstId,String nodeId,Short status){
        Map<String, Object> param = new HashMap<>(3);
        param.put("procInstId", procInstId);
        param.put("nodeId", nodeId);
        param.put("status", status);
        param.put("lastUpdateTime", new Date());
        return dao.updStatus(param);
    }

    /**
     * 根据流程实例id获取节点状态
     * @param procInstId 流程实例id
     * @return 节点状态列表
     */
    public List<BpmProStatus> queryByProcInstanceId(String procInstId){
        return dao.queryByProcInstanceId(procInstId);
    }

}
